<template>
  <div class="role-manage-container">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>角色管理</span>
          <el-button type="primary" v-permission="'system:role:add'" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            添加角色
          </el-button>
        </div>
      </template>

      <el-table :data="roleList" border style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="角色ID" width="100" />
        <el-table-column prop="roleName" label="角色名称" width="150" />
        <el-table-column prop="roleKey" label="角色标识" width="150" />
        <el-table-column label="权重" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getWeightTag(row.weight)">
              {{ row.weight || 0 }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="角色描述" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" fixed="right" width="300">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              v-permission="'system:role:edit'"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="warning"
              size="small"
              v-permission="'system:role:edit'"
              @click="handleAssignPermission(row)"
            >
              分配权限
            </el-button>
            <el-button
              type="danger"
              size="small"
              v-permission="'system:role:delete'"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑角色对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色标识" prop="roleKey">
          <el-input
            v-model="roleForm.roleKey"
            placeholder="请输入角色标识（如：admin）"
            :disabled="isEdit"
          />
        </el-form-item>
        <el-form-item label="角色权重" prop="weight">
          <el-input-number
            v-model="roleForm.weight"
            :min="0"
            :max="1000"
            :step="1"
            placeholder="数值越大权重越高"
            style="width: 100%"
          />
          <div style="margin-top: 5px; color: #909399; font-size: 12px;">
            权重值越大，角色权限越高。高权重角色可以向低权重角色发送通知。
          </div>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="roleForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="分配权限"
      width="600px"
      @close="resetPermissionForm"
    >
      <el-tree
        ref="menuTreeRef"
        :data="menuTreeData"
        :props="{ children: 'children', label: 'menuName' }"
        node-key="id"
        show-checkbox
        default-expand-all
        :default-checked-keys="checkedMenuIds"
      >
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <el-icon v-if="data.icon">
              <component :is="data.icon" />
            </el-icon>
            <span style="margin-left: 5px">{{ node.label }}</span>
            <el-tag size="small" style="margin-left: 10px" v-if="data.menuType === 1" type="primary">目录</el-tag>
            <el-tag size="small" style="margin-left: 10px" v-else-if="data.menuType === 2" type="success">菜单</el-tag>
            <el-tag size="small" style="margin-left: 10px" v-else type="info">按钮</el-tag>
          </span>
        </template>
      </el-tree>

      <template #footer>
        <el-button @click="permissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitPermission" :loading="permissionLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { getAllRoles, addRole, updateRole, deleteRole, assignMenusToRole } from '@/api/role'
import { getAllMenuTree } from '@/api/menu'
import { ElMessage, ElMessageBox } from 'element-plus'

const loading = ref(false)
const roleList = ref([])
const menuTreeData = ref([])
const menuTreeRef = ref(null)

const dialogVisible = ref(false)
const permissionDialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const submitLoading = ref(false)
const permissionLoading = ref(false)
const roleFormRef = ref(null)

const currentRoleId = ref(null)
const checkedMenuIds = ref([])

const roleForm = reactive({
  id: null,
  roleName: '',
  roleKey: '',
  weight: 0,
  description: '',
  status: 1
})

const roleRules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { max: 50, message: '角色名称长度不能超过50个字符', trigger: 'blur' }
  ],
  roleKey: [
    { required: true, message: '请输入角色标识', trigger: 'blur' },
    { max: 50, message: '角色标识长度不能超过50个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '角色标识只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '角色描述长度不能超过200个字符', trigger: 'blur' }
  ]
}

// 加载角色列表
const loadRoles = async () => {
  loading.value = true
  try {
    const res = await getAllRoles()
    if (res.code === 200) {
      roleList.value = res.data
    }
  } catch (error) {
    console.error('加载角色列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 加载菜单树
const loadMenuTree = async () => {
  try {
    const res = await getAllMenuTree()
    if (res.code === 200) {
      menuTreeData.value = res.data
    }
  } catch (error) {
    console.error('加载菜单树失败:', error)
  }
}

// 添加角色
const handleAdd = () => {
  dialogTitle.value = '添加角色'
  isEdit.value = false
  dialogVisible.value = true
}

// 编辑角色
const handleEdit = (row) => {
  dialogTitle.value = '编辑角色'
  isEdit.value = true
  roleForm.id = row.id
  roleForm.roleName = row.roleName
  roleForm.roleKey = row.roleKey
  roleForm.weight = row.weight || 0
  roleForm.description = row.description
  roleForm.status = row.status
  dialogVisible.value = true
}

// 删除角色
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除角色"${row.roleName}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteRole(row.id)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        loadRoles()
      }
    } catch (error) {
      console.error('删除角色失败:', error)
    }
  }).catch(() => {
    // 取消删除
  })
}

// 分配权限
const handleAssignPermission = async (row) => {
  currentRoleId.value = row.id
  
  // 加载菜单树
  await loadMenuTree()
  
  // 设置已选中的菜单（只设置叶子节点，避免父节点的子节点全部被勾选）
  const leafNodeIds = getLeafNodeIds(menuTreeData.value, row.menuIds || [])
  checkedMenuIds.value = leafNodeIds
  
  permissionDialogVisible.value = true
}

// 获取叶子节点ID（递归获取没有children的节点）
const getLeafNodeIds = (treeData, selectedIds) => {
  const leafIds = []
  
  const traverse = (nodes) => {
    for (const node of nodes) {
      // 如果该节点被选中
      if (selectedIds.includes(node.id)) {
        // 如果没有子节点或子节点为空数组，则是叶子节点
        if (!node.children || node.children.length === 0) {
          leafIds.push(node.id)
        } else {
          // 如果有子节点，继续遍历子节点
          traverse(node.children)
        }
      }
    }
  }
  
  traverse(treeData)
  return leafIds
}

// 提交表单
const submitForm = async () => {
  if (!roleFormRef.value) return

  await roleFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        const data = {
          ...roleForm
        }
        
        let res
        if (isEdit.value) {
          res = await updateRole(data)
        } else {
          res = await addRole(data)
        }

        if (res.code === 200) {
          ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
          dialogVisible.value = false
          loadRoles()
        }
      } catch (error) {
        console.error('操作失败:', error)
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 提交权限分配
const submitPermission = async () => {
  permissionLoading.value = true
  try {
    // 获取选中的菜单ID（包括半选中的父节点）
    const checkedKeys = menuTreeRef.value.getCheckedKeys()
    const halfCheckedKeys = menuTreeRef.value.getHalfCheckedKeys()
    const menuIds = [...checkedKeys, ...halfCheckedKeys]
    
    const res = await assignMenusToRole(currentRoleId.value, menuIds)
    if (res.code === 200) {
      ElMessage.success('分配权限成功')
      permissionDialogVisible.value = false
      loadRoles()
    }
  } catch (error) {
    console.error('分配权限失败:', error)
  } finally {
    permissionLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  roleForm.id = null
  roleForm.roleName = ''
  roleForm.roleKey = ''
  roleForm.weight = 0
  roleForm.description = ''
  roleForm.status = 1
  
  if (roleFormRef.value) {
    roleFormRef.value.resetFields()
  }
}

// 获取权重标签类型
const getWeightTag = (weight) => {
  if (!weight || weight === 0) return ''
  if (weight >= 100) return 'danger'
  if (weight >= 50) return 'warning'
  if (weight >= 10) return 'success'
  return 'info'
}

// 重置权限表单
const resetPermissionForm = () => {
  currentRoleId.value = null
  checkedMenuIds.value = []
}

onMounted(() => {
  loadRoles()
})
</script>

<style scoped>
.role-manage-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.custom-tree-node {
  display: flex;
  align-items: center;
}

/* 深色模式适配 */
html.dark :deep(.el-form-item__content > div) {
  color: var(--el-text-color-regular);
}
</style>